package com.hanhai.zrb.mobile.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hanhai.common.annotation.LoginNeedless;
import com.hanhai.common.web.controller.BaseController;
import com.hanhai.zrb.api.biz.service.BusinessCardService;
import com.hanhai.zrb.api.biz.service.CityInfoService;
import com.hanhai.zrb.api.biz.service.CommonCounterService;
import com.hanhai.zrb.api.biz.service.FundService;
import com.hanhai.zrb.api.biz.service.IndustryService;
import com.hanhai.zrb.api.biz.service.ProjectService;
import com.hanhai.zrb.api.biz.service.UserFollowService;
import com.hanhai.zrb.api.biz.service.UserInfoService;
import com.hanhai.zrb.api.biz.service.UserService;
import com.hanhai.zrb.api.client.facade.FundFacade;
import com.hanhai.zrb.mobile.result.BaseApiResult;
import com.hanhai.zrb.mobile.util.FrontLoginUtil;
import com.hanhai.zrb.model.common.BaseUser;
import com.hanhai.zrb.model.common.enums.StatusEnums;
import com.hanhai.zrb.model.fund.Fund;
import com.hanhai.zrb.model.project.Project;
import com.hanhai.zrb.model.user.User;
import com.hanhai.zrb.model.user.UserBase;
import com.hanhai.zrb.model.user.enums.UserFollowRelationEnum;
import com.hanhai.zrb.model.user.enums.UserInfoName;
import com.hanhai.zrb.model.user.vo.BusinessCardVO;
import com.hanhai.zrb.model.user.vo.UserInfoVO;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiResponse;
import com.wordnik.swagger.annotations.ApiResponses;
@Controller
@RequestMapping("/businessCard")
public class BusinessCardController extends BaseController{
	
	
	
	@Resource
	private UserService userService;
	
	@Resource
	private UserInfoService userInfoService;
	
	@Resource
	private FundService fundService;
	
	@Resource
	private IndustryService industryService;
	
	@Resource
	private ProjectService projectService;
	
	@Resource
	private CityInfoService cityInfoService;
	
	@Resource
	private FundFacade fundFacade;
	
	@Resource
	private CommonCounterService commonCounterService;
	
	@Resource
	private BusinessCardService businessCardService;
	
	@Resource
	private UserFollowService userFollowService;
	
	@ResponseBody
	@ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input") })
	@ApiOperation(value = "查询我的名片基本信息",  response = BaseApiResult.class, notes = "查询我的名片基本信息")
	@RequestMapping(value="/myCard")
	public BaseApiResult list(HttpServletRequest request,HttpServletResponse response,@RequestParam(value="userId", required=true)Long userId){
		BaseUser user = FrontLoginUtil.getCurrentUser();
		BaseApiResult result = new BaseApiResult();
	    /*User user = userService.findById(userId);
	    Map<String, Object> data = new HashMap<String, Object>();
	    if(null!=user && !"".equals(user)){
	    	data.put("Uid",user.getUid());
	    	data.put("Industry",user.getIndustry());
	    	data.put("realname",user.getRealname());
	    	data.put("IndustryId",user.getIndustryId());
	    	data.put("Org",user.getOrg());
	    	data.put("Umobile",getStartPhone(user.getUmobile()));
	    	data.put("Avatar",user.getAvatar());
			List<UserInfoName> queryNameList = new ArrayList<UserInfoName>();
			queryNameList.add(UserInfoName.POSITION);
			UserInfoVO userInfoVo = userInfoService.findByNameEnums(Long.toString(user.getUid()), queryNameList);
			Map<String, String> infoMap = userInfoVo.getInfoMap();
			String position = infoMap.get("POSITION");
			data.put("position", position);	
	    }*/
		BusinessCardVO bvo = businessCardService
				.getUserBusinessCardFromCache(userId);

		{
			//判断关注状态
			Integer relationCode = userFollowService.relation(user.getUid(),
					userId);

			UserFollowRelationEnum relation = UserFollowRelationEnum
					.getEnumByCode(relationCode);
			if (relation == null) {
				relation = UserFollowRelationEnum.NONE;
			}
			bvo.setRelationCode(relation.getCode());
			bvo.setRelationName(relation.getValue());
		}
		result.setData(bvo);
		result.setRes(1);
		logger.info("businessCard / myCard  successed");
		return result;
	}
	
	@RequestMapping("/getProjectUserInfo")
	@ResponseBody
	@LoginNeedless
	public BaseApiResult getProjectUserInfo(Long projectId){
		BaseApiResult ret = new BaseApiResult();
		
		
		Project project = projectService.selectByPrimaryKey(projectId);
		
		if(project.getProjectStatus()==StatusEnums.RELEASE.getCode().shortValue()){
			String userIdStr = project.getPusher();
			if(StringUtils.isNoneBlank(userIdStr)&&StringUtils.isNumeric(userIdStr)){
				User user = userService.findById(Long.valueOf(userIdStr));
				if(user !=null){
					UserBase userBase = new UserBase();
					userBase.setUid(user.getUid());
					userBase.setIndustryId(user.getIndustryId());
					userBase.setIndustryName(user.getIndustry());
					userBase.setRealName(user.getRealname());
					userBase.setUmobile(user.getUmobile());
					userBase.setOrg(user.getOrg());
					userBase.setAvatar(user.getAvatar());

					//获取用户职位
					List<UserInfoName> queryNameList = new ArrayList<UserInfoName>();
					queryNameList.add(UserInfoName.POSITION);
					UserInfoVO userInfoVo = userInfoService.findByNameEnums(
							Long.toString(user.getUid()), queryNameList);
					Map<String, String> infoMap = userInfoVo.getInfoMap();
					String position = infoMap.get("POSITION");
					userBase.setPosition(position);
					ret.setData(userBase);
					return ret;
				}
				
			}
		}
		
		ret.setRes(0);
		ret.setMsg("无效数据，请刷新再试");
		return ret;
		
	}
	
	@RequestMapping("/getFundUserInfo")
	@ResponseBody
	@LoginNeedless
	public BaseApiResult getFundUserInfo(Long fundId){
		BaseApiResult ret = new BaseApiResult();
		
		Fund fund = fundService.findById(fundId);
		
		if(fund.getState()==StatusEnums.RELEASE.getCode().shortValue()){
			Long userId = fund.getUserId();
				User user = userService.findById(userId);
				if(user !=null){
					UserBase userBase = new UserBase();
					userBase.setUid(user.getUid());
					userBase.setIndustryId(user.getIndustryId());
					userBase.setIndustryName(user.getIndustry());
					userBase.setRealName(user.getRealname());
					userBase.setUmobile(user.getUmobile());
					userBase.setOrg(user.getOrg());
					userBase.setAvatar(user.getAvatar());

					//获取用户职位
					List<UserInfoName> queryNameList = new ArrayList<UserInfoName>();
					queryNameList.add(UserInfoName.POSITION);
					UserInfoVO userInfoVo = userInfoService.findByNameEnums(
							Long.toString(user.getUid()), queryNameList);
					Map<String, String> infoMap = userInfoVo.getInfoMap();
					String position = infoMap.get("POSITION");
					userBase.setPosition(position);
					ret.setData(userBase);
					return ret;
				}
				
			
		}
		
		ret.setRes(0);
		ret.setMsg("无效数据，请刷新再试");
		return ret;
		
	}
	
	/*@LoginNeedless
	@ResponseBody
	@ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input") })
	@ApiOperation(value = "查询我的名片发布资金信息",  response = BaseApiResult.class, notes = "查询我的名片发布资金信息")
	@RequestMapping(value="/queryFundList")
	public BaseApiResult queryFundList(HttpServletRequest request,HttpServletResponse response,@RequestParam(value="userId", required=true)Long userId,Long pushTime, Integer limit){
	    BaseApiResult result = new BaseApiResult();
	    List<Map<String,Object>> list =new ArrayList<Map<String,Object>>();
		FundDto fundDto = new FundDto();
		Date date = (null==pushTime?null:DateUtil.getStringToDate(DateUtil.FULL_ST_FORMAT,DateUtil.getDate(pushTime)));
		fundDto.setEndTime(date);
		fundDto.setUserId(userId);
		fundDto.setState(StatusEnums.RELEASE.getCode());
		fundDto.setPageNum(1);
		fundDto.setPageSize(limit);
		List<Fund> fundList = fundService.queryByCondition(fundDto);
	    //查询所有行业
		Map<Integer,Industry>  industryMap = industryService.selectAllMap();
		//查询所有区域
		Map<String,CityInfo>  cityInfoMap = cityInfoService.selectAllMap();


		
		if(CollectionUtils.isNotEmpty(fundList)){
			for(Fund fund:fundList){
				Map<String,Object> map = new HashMap<String, Object>();
				map.put("id",fund.getId().toString());
				map.put("title",fund.getTitlesVal());
				map.put("total", fund.getTotal().toString());
				map.put("auth", fund.getAuth().toString());
				if("502".equals(fund.getAuth().toString())){
					map.put("authName", "实地认证");
				}
				if("503".equals(fund.getAuth().toString())){
					map.put("authName", "资料认证");
				}
//				SimpleDateFormat formatter = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
//				String str ="";
//				if(null!=fund.getPushTime()){
//					str = formatter.format(fund.getPushTime());
//				}
				map.put("pushTime",fund.getPushTime());
				CommonCounterKey commonCounterKey = new CommonCounterKey();
				commonCounterKey.setMainKey(UserStatisticDetail.Type.fund_col.getCountKey());
				commonCounterKey.setSecondaryKey(fund.getId().toString());
				map.put("collectNum",commonCounterService.getCurrentCountByKey(commonCounterKey).toString());
				commonCounterKey.setMainKey(UserStatisticDetail.Type.fund_query.getCountKey());
				map.put("queryNum",commonCounterService.getCurrentCountByKey(commonCounterKey).toString());
				
				map.put("industry", getIndustryNameStr(fund.getIndustryId(),industryMap));
				map.put("cityInfo", getCityInfoNameStr(fund.getDestination(), cityInfoMap));
				list.add(map);
			}
		}
		
        result.setData(list);
		result.setRes(1);
		logger.info("businessCard / queryFundList  successed");
		return result;
	}
	
	
	private  String getStartPhone(String phone){
		String rs = "***";
        if(StringUtils.isNotBlank(phone) ){
        	if(phone.length()==11){
        		rs=phone.substring(0,phone.length() - (phone.substring(3)).length()) +"****"+phone.substring(7);
        	}else{
        		rs=phone.substring(0,phone.length() - 1) +"****";
        	}
        	 
        }	
		return rs;
	}
	
	private static String getIndustryNameStr(String industryId,Map<Integer,Industry> industryMap){
		String val ="";
		if(StringUtils.isNotBlank(industryId)){
			  String[] industryStr = industryId.split("#");
			  for (int k = 0; k < industryStr.length; k++) {
				 if(StringUtils.isNumeric(industryStr[k]) && null!=industryMap.get(Integer.valueOf(industryStr[k])) && !"".equals(industryMap.get(Integer.valueOf(industryStr[k])))){
					 if((industryStr.length)-1!=k){
						 val = val + industryMap.get(Integer.valueOf(industryStr[k])).getIndustryName()+"#"; 
					 }else{
						 val = val + industryMap.get(Integer.valueOf(industryStr[k])).getIndustryName();
					 }
				
				 }
                 
			}
		}
		return val;
		
	}
	
	private static String getCityInfoNameStr(String cityInfoId,Map<String,CityInfo> map){

		String val ="";
		if(StringUtils.isNotBlank(cityInfoId)){
			  String[] cityStr = cityInfoId.split("#");
			  for (int k = 0; k < cityStr.length; k++) {
				 if(StringUtils.isNumeric(cityStr[k]) && null!=map.get(cityStr[k]) && !"".equals(map.get(cityStr[k]))){
					 if((cityStr.length)-1!=k ){

					      val = val + map.get(cityStr[k]).getCityName()+"#"; 
					 }else{
						 val = val + map.get(cityStr[k]).getCityName();  
					 }
				 }
               
			}

		}

		return val;
		
	}
	*/
	
	

}
